<!DOCTYPE html>
<html lang="en">


<!-- Mirrored from www.django-rest-framework.org/api-guide/filtering/ by HTTrack Website Copier/3.x [XR&CO'2014], Sun, 13 Sep 2020 09:30:50 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=utf-8" /><!-- /Added by HTTrack -->
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <title>Filtering - Django REST framework</title>
  <link href="../../img/favicon.ico" rel="icon" type="image/x-icon">
  <link rel="canonical" href="index.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="Django, API, REST, Filtering">
  <meta name="author" content="Tom Christie">

  <!-- Le styles -->
  <link href="../../css/prettify.css" rel="stylesheet">
  <link href="../../css/bootstrap.css" rel="stylesheet">
  <link href="../../css/bootstrap-responsive.css" rel="stylesheet">
  <link href="../../css/default.css" rel="stylesheet">


  <script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-18852272-2']);
    _gaq.push(['_trackPageview']);

    (function() {
      var ga = document.createElement('script');
      ga.type = 'text/javascript';
      ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ga, s);
    })();
  </script>

  <style>
  #sidebarInclude img {
      margin-bottom: 10px;
  }
  #sidebarInclude a.promo {
      color: black;
  }
    @media (max-width: 767px) {
      div.promo {
        display: none;
      }
    }
  </style>
</head>
<body onload="prettyPrint()" class="-page">

  <div class="wrapper">
        <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container-fluid">
          <a class="repo-link btn btn-primary btn-small" href="https://github.com/encode/django-rest-framework/tree/master">GitHub</a>
          <a class="repo-link btn btn-inverse btn-small " rel="next" href="../pagination/index.html">
            Next <i class="icon-arrow-right icon-white"></i>
          </a>
          <a class="repo-link btn btn-inverse btn-small " rel="prev" href="../throttling/index.html">
            <i class="icon-arrow-left icon-white"></i> Previous
          </a>
          <a id="search_modal_show" class="repo-link btn btn-inverse btn-small" href="#mkdocs_search_modal" data-toggle="modal" data-target="#mkdocs_search_modal"><i class="icon-search icon-white"></i> Search</a>
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </a>
          <a class="brand" href="../../index.html">Django REST framework</a>
          <div class="nav-collapse collapse">
            
            <!-- Main navigation -->
            <ul class="nav navbar-nav">
               
              <li >
                <a href="../../index.html">Home</a>
              </li>
                
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../../tutorial/quickstart/index.html">Quickstart</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/1-serialization/index.html">1 - Serialization</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/2-requests-and-responses/index.html">2 - Requests and responses</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/3-class-based-views/index.html">3 - Class based views</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/4-authentication-and-permissions/index.html">4 - Authentication and permissions</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/5-relationships-and-hyperlinked-apis/index.html">5 - Relationships and hyperlinked APIs</a>
                  </li>
                  
                  <li >
                    <a href="../../tutorial/6-viewsets-and-routers/index.html">6 - Viewsets and routers</a>
                  </li>
                  
                </ul>
              </li>
                
              <li class="dropdown active">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../requests/index.html">Requests</a>
                  </li>
                  
                  <li >
                    <a href="../responses/index.html">Responses</a>
                  </li>
                  
                  <li >
                    <a href="../views/index.html">Views</a>
                  </li>
                  
                  <li >
                    <a href="../generic-views/index.html">Generic views</a>
                  </li>
                  
                  <li >
                    <a href="../viewsets/index.html">Viewsets</a>
                  </li>
                  
                  <li >
                    <a href="../routers/index.html">Routers</a>
                  </li>
                  
                  <li >
                    <a href="../parsers/index.html">Parsers</a>
                  </li>
                  
                  <li >
                    <a href="../renderers/index.html">Renderers</a>
                  </li>
                  
                  <li >
                    <a href="../serializers/index.html">Serializers</a>
                  </li>
                  
                  <li >
                    <a href="../fields/index.html">Serializer fields</a>
                  </li>
                  
                  <li >
                    <a href="../relations/index.html">Serializer relations</a>
                  </li>
                  
                  <li >
                    <a href="../validators/index.html">Validators</a>
                  </li>
                  
                  <li >
                    <a href="../authentication/index.html">Authentication</a>
                  </li>
                  
                  <li >
                    <a href="../permissions/index.html">Permissions</a>
                  </li>
                  
                  <li >
                    <a href="../caching/index.html">Caching</a>
                  </li>
                  
                  <li >
                    <a href="../throttling/index.html">Throttling</a>
                  </li>
                  
                  <li class="active" >
                    <a href="index.html">Filtering</a>
                  </li>
                  
                  <li >
                    <a href="../pagination/index.html">Pagination</a>
                  </li>
                  
                  <li >
                    <a href="../versioning/index.html">Versioning</a>
                  </li>
                  
                  <li >
                    <a href="../content-negotiation/index.html">Content negotiation</a>
                  </li>
                  
                  <li >
                    <a href="../metadata/index.html">Metadata</a>
                  </li>
                  
                  <li >
                    <a href="../schemas/index.html">Schemas</a>
                  </li>
                  
                  <li >
                    <a href="../format-suffixes/index.html">Format suffixes</a>
                  </li>
                  
                  <li >
                    <a href="../reverse/index.html">Returning URLs</a>
                  </li>
                  
                  <li >
                    <a href="../exceptions/index.html">Exceptions</a>
                  </li>
                  
                  <li >
                    <a href="../status-codes/index.html">Status codes</a>
                  </li>
                  
                  <li >
                    <a href="../testing/index.html">Testing</a>
                  </li>
                  
                  <li >
                    <a href="../settings/index.html">Settings</a>
                  </li>
                  
                </ul>
              </li>
                
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../../topics/documenting-your-api/index.html">Documenting your API</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/api-clients/index.html">API Clients</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/internationalization/index.html">Internationalization</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/ajax-csrf-cors/index.html">AJAX, CSRF & CORS</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/html-and-forms/index.html">HTML & Forms</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/browser-enhancements/index.html">Browser Enhancements</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/browsable-api/index.html">The Browsable API</a>
                  </li>
                  
                  <li >
                    <a href="../../topics/rest-hypermedia-hateoas/index.html">REST, Hypermedia & HATEOAS</a>
                  </li>
                  
                </ul>
              </li>
                
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Community <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  
                  <li >
                    <a href="../../community/tutorials-and-resources/index.html">Tutorials and Resources</a>
                  </li>
                  
                  <li >
                    <a href="../../community/third-party-packages/index.html">Third Party Packages</a>
                  </li>
                  
                  <li >
                    <a href="../../community/contributing/index.html">Contributing to REST framework</a>
                  </li>
                  
                  <li >
                    <a href="../../community/project-management/index.html">Project management</a>
                  </li>
                  
                  <li >
                    <a href="../../community/release-notes/index.html">Release Notes</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.11-announcement/index.html">3.11 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.10-announcement/index.html">3.10 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.9-announcement/index.html">3.9 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.8-announcement/index.html">3.8 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.7-announcement/index.html">3.7 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.6-announcement/index.html">3.6 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.5-announcement/index.html">3.5 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.4-announcement/index.html">3.4 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.3-announcement/index.html">3.3 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.2-announcement/index.html">3.2 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.1-announcement/index.html">3.1 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/3.0-announcement/index.html">3.0 Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/kickstarter-announcement/index.html">Kickstarter Announcement</a>
                  </li>
                  
                  <li >
                    <a href="../../community/mozilla-grant/index.html">Mozilla Grant</a>
                  </li>
                  
                  <li >
                    <a href="../../community/funding/index.html">Funding</a>
                  </li>
                  
                  <li >
                    <a href="../../community/jobs/index.html">Jobs</a>
                  </li>
                  
                </ul>
              </li>
               

            </ul>
            
          </div>
          <!--/.nav-collapse -->

        </div>
      </div>
    </div>

    <div class="body-content">
      <div class="container-fluid">
        <!-- Search Modal -->
        <div id="mkdocs_search_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3 id="myModalLabel">Documentation search</h3>
          </div>

          <div class="modal-body">
            <form role="form" autocomplete="off">
              <div class="form-group">
                <input type="text" name="q" class="form-control" placeholder="Search..." id="mkdocs-search-query">
              </div>
            </form>
            <div id="mkdocs-search-results"></div>
          </div>

          <div class="modal-footer">
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
          </div>
        </div>

        <div class="row-fluid">
          <div class="span3">
            <div id="table-of-contents">
              <ul class="nav nav-list side-nav well sidebar-nav-fixed">
                

                
                  <li class="main">
                    <a href="#filtering">Filtering</a>
                  </li>

                  
                    <li>
                      <a href="#filtering-against-the-current-user">Filtering against the current user</a>
                    </li>
                  
                    <li>
                      <a href="#filtering-against-the-url">Filtering against the URL</a>
                    </li>
                  
                    <li>
                      <a href="#filtering-against-query-parameters">Filtering against query parameters</a>
                    </li>
                  
                
                  <li class="main">
                    <a href="#generic-filtering">Generic Filtering</a>
                  </li>

                  
                    <li>
                      <a href="#setting-filter-backends">Setting filter backends</a>
                    </li>
                  
                    <li>
                      <a href="#filtering-and-object-lookups">Filtering and object lookups</a>
                    </li>
                  
                    <li>
                      <a href="#overriding-the-initial-queryset">Overriding the initial queryset</a>
                    </li>
                  
                
                  <li class="main">
                    <a href="#api-guide">API Guide</a>
                  </li>

                  
                    <li>
                      <a href="#djangofilterbackend">DjangoFilterBackend</a>
                    </li>
                  
                    <li>
                      <a href="#searchfilter">SearchFilter</a>
                    </li>
                  
                    <li>
                      <a href="#orderingfilter">OrderingFilter</a>
                    </li>
                  
                
                  <li class="main">
                    <a href="#custom-generic-filtering">Custom generic filtering</a>
                  </li>

                  
                    <li>
                      <a href="#example">Example</a>
                    </li>
                  
                    <li>
                      <a href="#customizing-the-interface">Customizing the interface</a>
                    </li>
                  
                    <li>
                      <a href="#pagination-schemas">Pagination &amp; schemas</a>
                    </li>
                  
                
                  <li class="main">
                    <a href="#third-party-packages">Third party packages</a>
                  </li>

                  
                    <li>
                      <a href="#django-rest-framework-filters-package">Django REST framework filters package</a>
                    </li>
                  
                    <li>
                      <a href="#django-rest-framework-full-word-search-filter">Django REST framework full word search filter</a>
                    </li>
                  
                    <li>
                      <a href="#django-url-filter">Django URL Filter</a>
                    </li>
                  
                    <li>
                      <a href="#drf-url-filters">drf-url-filters</a>
                    </li>
                  
                

                  <div class="promo">
                    <hr/>
                    <div id="sidebarInclude">
                  </div>
              </ul>

            </div>
          </div>

          <div id="main-content" class="span9">
            
              
                
                  <a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/filters.py">
                    <span class="label label-info">filters.py</span>
                  </a>
                
              

              <h1 id="filtering"><a class="toclink" href="#filtering">Filtering</a></h1>
<blockquote>
<p>The root QuerySet provided by the Manager describes all objects in the database table.  Usually, though, you'll need to select only a subset of the complete set of objects.</p>
<p>&mdash; <a href="https://docs.djangoproject.com/en/stable/topics/db/queries/#retrieving-specific-objects-with-filters">Django documentation</a></p>
</blockquote>
<p>The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.  Often you will want your API to restrict the items that are returned by the queryset.</p>
<p>The simplest way to filter the queryset of any view that subclasses <code>GenericAPIView</code> is to override the <code>.get_queryset()</code> method.</p>
<p>Overriding this method allows you to customize the queryset returned by the view in a number of different ways.</p>
<h2 id="filtering-against-the-current-user"><a class="toclink" href="#filtering-against-the-current-user">Filtering against the current user</a></h2>
<p>You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.</p>
<p>You can do so by filtering based on the value of <code>request.user</code>.</p>
<p>For example:</p>
<pre><code>from myapp.models import Purchase
from myapp.serializers import PurchaseSerializer
from rest_framework import generics

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        This view should return a list of all the purchases
        for the currently authenticated user.
        """
        user = self.request.user
        return Purchase.objects.filter(purchaser=user)
</code></pre>
<h2 id="filtering-against-the-url"><a class="toclink" href="#filtering-against-the-url">Filtering against the URL</a></h2>
<p>Another style of filtering might involve restricting the queryset based on some part of the URL.</p>
<p>For example if your URL config contained an entry like this:</p>
<pre><code>url('^purchases/(?P&lt;username&gt;.+)/$', PurchaseList.as_view()),
</code></pre>
<p>You could then write a view that returned a purchase queryset filtered by the username portion of the URL:</p>
<pre><code>class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        This view should return a list of all the purchases for
        the user as determined by the username portion of the URL.
        """
        username = self.kwargs['username']
        return Purchase.objects.filter(purchaser__username=username)
</code></pre>
<h2 id="filtering-against-query-parameters"><a class="toclink" href="#filtering-against-query-parameters">Filtering against query parameters</a></h2>
<p>A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.</p>
<p>We can override <code>.get_queryset()</code> to deal with URLs such as <code>http://example.com/api/purchases?username=denvercoder9</code>, and filter the queryset only if the <code>username</code> parameter is included in the URL:</p>
<pre><code>class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        Optionally restricts the returned purchases to a given user,
        by filtering against a `username` query parameter in the URL.
        """
        queryset = Purchase.objects.all()
        username = self.request.query_params.get('username', None)
        if username is not None:
            queryset = queryset.filter(purchaser__username=username)
        return queryset
</code></pre>
<hr />
<h1 id="generic-filtering"><a class="toclink" href="#generic-filtering">Generic Filtering</a></h1>
<p>As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.</p>
<p>Generic filters can also present themselves as HTML controls in the browsable API and admin API.</p>
<p><img alt="Filter Example" src="../../img/filter-controls.png" /></p>
<h2 id="setting-filter-backends"><a class="toclink" href="#setting-filter-backends">Setting filter backends</a></h2>
<p>The default filter backends may be set globally, using the <code>DEFAULT_FILTER_BACKENDS</code> setting. For example.</p>
<pre><code>REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
</code></pre>
<p>You can also set the filter backends on a per-view, or per-viewset basis,
using the <code>GenericAPIView</code> class-based views.</p>
<pre><code>import django_filters.rest_framework
from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
from rest_framework import generics

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
</code></pre>
<h2 id="filtering-and-object-lookups"><a class="toclink" href="#filtering-and-object-lookups">Filtering and object lookups</a></h2>
<p>Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.</p>
<p>For instance, given the previous example, and a product with an id of <code>4675</code>, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:</p>
<pre><code>http://example.com/api/products/4675/?category=clothing&amp;max_price=10.00
</code></pre>
<h2 id="overriding-the-initial-queryset"><a class="toclink" href="#overriding-the-initial-queryset">Overriding the initial queryset</a></h2>
<p>Note that you can use both an overridden <code>.get_queryset()</code> and generic filtering together, and everything will work as expected.  For example, if <code>Product</code> had a many-to-many relationship with <code>User</code>, named <code>purchase</code>, you might want to write a view like this:</p>
<pre><code>class PurchasedProductsList(generics.ListAPIView):
    """
    Return a list of all the products that the authenticated
    user has ever purchased, with optional filtering.
    """
    model = Product
    serializer_class = ProductSerializer
    filterset_class = ProductFilter

    def get_queryset(self):
        user = self.request.user
        return user.purchase_set.all()
</code></pre>
<hr />
<h1 id="api-guide"><a class="toclink" href="#api-guide">API Guide</a></h1>
<h2 id="djangofilterbackend"><a class="toclink" href="#djangofilterbackend">DjangoFilterBackend</a></h2>
<p>The <a href="https://django-filter.readthedocs.io/en/latest/index.html"><code>django-filter</code></a> library includes a <code>DjangoFilterBackend</code> class which
supports highly customizable field filtering for REST framework.</p>
<p>To use <code>DjangoFilterBackend</code>, first install <code>django-filter</code>. Then add <code>django_filters</code> to Django's <code>INSTALLED_APPS</code></p>
<pre><code>pip install django-filter
</code></pre>
<p>You should now either add the filter backend to your settings:</p>
<pre><code>REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
</code></pre>
<p>Or add the filter backend to an individual View or ViewSet.</p>
<pre><code>from django_filters.rest_framework import DjangoFilterBackend

class UserListView(generics.ListAPIView):
    ...
    filter_backends = [DjangoFilterBackend]
</code></pre>
<p>If all you need is simple equality-based filtering, you can set a <code>filterset_fields</code> attribute on the view, or viewset, listing the set of fields you wish to filter against.</p>
<pre><code>class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['category', 'in_stock']
</code></pre>
<p>This will automatically create a <code>FilterSet</code> class for the given fields, and will allow you to make requests such as:</p>
<pre><code>http://example.com/api/products?category=clothing&amp;in_stock=True
</code></pre>
<p>For more advanced filtering requirements you can specify a <code>FilterSet</code> class that should be used by the view.
You can read more about <code>FilterSet</code>s in the <a href="https://django-filter.readthedocs.io/en/latest/index.html">django-filter documentation</a>.
It's also recommended that you read the section on <a href="https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html">DRF integration</a>.</p>
<h2 id="searchfilter"><a class="toclink" href="#searchfilter">SearchFilter</a></h2>
<p>The <code>SearchFilter</code> class supports simple single query parameter based searching, and is based on the <a href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields">Django admin's search functionality</a>.</p>
<p>When in use, the browsable API will include a <code>SearchFilter</code> control:</p>
<p><img alt="Search Filter" src="../../img/search-filter.png" /></p>
<p>The <code>SearchFilter</code> class will only be applied if the view has a <code>search_fields</code> attribute set.  The <code>search_fields</code> attribute should be a list of names of text type fields on the model, such as <code>CharField</code> or <code>TextField</code>.</p>
<pre><code>from rest_framework import filters

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['username', 'email']
</code></pre>
<p>This will allow the client to filter the items in the list by making queries such as:</p>
<pre><code>http://example.com/api/users?search=russell
</code></pre>
<p>You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:</p>
<pre><code>search_fields = ['username', 'email', 'profile__profession']
</code></pre>
<p>For <a href="https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield">JSONField</a> and <a href="https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield">HStoreField</a> fields you can filter based on nested values within the data structure using the same double-underscore notation:</p>
<pre><code>search_fields = ['data__breed', 'data__owner__other_pets__0__name']
</code></pre>
<p>By default, searches will use case-insensitive partial matches.  The search parameter may contain multiple search terms, which should be whitespace and/or comma separated.  If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.</p>
<p>The search behavior may be restricted by prepending various characters to the <code>search_fields</code>.</p>
<ul>
<li>'^' Starts-with search.</li>
<li>'=' Exact matches.</li>
<li>'@' Full-text search.  (Currently only supported Django's <a href="https://docs.djangoproject.com/en/dev/ref/contrib/postgres/search/">PostgreSQL backend</a>.)</li>
<li>'$' Regex search.</li>
</ul>
<p>For example:</p>
<pre><code>search_fields = ['=username', '=email']
</code></pre>
<p>By default, the search parameter is named <code>'search'</code>, but this may be overridden with the <code>SEARCH_PARAM</code> setting.</p>
<p>To dynamically change search fields based on request content, it's possible to subclass the <code>SearchFilter</code> and override the <code>get_search_fields()</code> function. For example, the following subclass will only search on <code>title</code> if the query parameter <code>title_only</code> is in the request:</p>
<pre><code>from rest_framework import filters

class CustomSearchFilter(filters.SearchFilter):
    def get_search_fields(self, view, request):
        if request.query_params.get('title_only'):
            return ['title']
        return super(CustomSearchFilter, self).get_search_fields(view, request)
</code></pre>
<p>For more details, see the <a href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields">Django documentation</a>.</p>
<hr />
<h2 id="orderingfilter"><a class="toclink" href="#orderingfilter">OrderingFilter</a></h2>
<p>The <code>OrderingFilter</code> class supports simple query parameter controlled ordering of results.</p>
<p><img alt="Ordering Filter" src="../../img/ordering-filter.png" /></p>
<p>By default, the query parameter is named <code>'ordering'</code>, but this may by overridden with the <code>ORDERING_PARAM</code> setting.</p>
<p>For example, to order users by username:</p>
<pre><code>http://example.com/api/users?ordering=username
</code></pre>
<p>The client may also specify reverse orderings by prefixing the field name with '-', like so:</p>
<pre><code>http://example.com/api/users?ordering=-username
</code></pre>
<p>Multiple orderings may also be specified:</p>
<pre><code>http://example.com/api/users?ordering=account,username
</code></pre>
<h3 id="specifying-which-fields-may-be-ordered-against"><a class="toclink" href="#specifying-which-fields-may-be-ordered-against">Specifying which fields may be ordered against</a></h3>
<p>It's recommended that you explicitly specify which fields the API should allowing in the ordering filter.  You can do this by setting an <code>ordering_fields</code> attribute on the view, like so:</p>
<pre><code>class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['username', 'email']
</code></pre>
<p>This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.</p>
<p>If you <em>don't</em> specify an <code>ordering_fields</code> attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the <code>serializer_class</code> attribute.</p>
<p>If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on <em>any</em> model field or queryset aggregate, by using the special value <code>'__all__'</code>.</p>
<pre><code>class BookingsListView(generics.ListAPIView):
    queryset = Booking.objects.all()
    serializer_class = BookingSerializer
    filter_backends = [filters.OrderingFilter]
    ordering_fields = '__all__'
</code></pre>
<h3 id="specifying-a-default-ordering"><a class="toclink" href="#specifying-a-default-ordering">Specifying a default ordering</a></h3>
<p>If an <code>ordering</code> attribute is set on the view, this will be used as the default ordering.</p>
<p>Typically you'd instead control this by setting <code>order_by</code> on the initial queryset, but using the <code>ordering</code> parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template.  This makes it possible to automatically render column headers differently if they are being used to order the results.</p>
<pre><code>class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['username', 'email']
    ordering = ['username']
</code></pre>
<p>The <code>ordering</code> attribute may be either a string or a list/tuple of strings.</p>
<hr />
<h1 id="custom-generic-filtering"><a class="toclink" href="#custom-generic-filtering">Custom generic filtering</a></h1>
<p>You can also provide your own generic filtering backend, or write an installable app for other developers to use.</p>
<p>To do so override <code>BaseFilterBackend</code>, and override the <code>.filter_queryset(self, request, queryset, view)</code> method.  The method should return a new, filtered queryset.</p>
<p>As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.</p>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>For example, you might need to restrict users to only being able to see objects they created.</p>
<pre><code>class IsOwnerFilterBackend(filters.BaseFilterBackend):
    """
    Filter that only allows users to see their own objects.
    """
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(owner=request.user)
</code></pre>
<p>We could achieve the same behavior by overriding <code>get_queryset()</code> on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.</p>
<h2 id="customizing-the-interface"><a class="toclink" href="#customizing-the-interface">Customizing the interface</a></h2>
<p>Generic filters may also present an interface in the browsable API. To do so you should implement a <code>to_html()</code> method which returns a rendered HTML representation of the filter. This method should have the following signature:</p>
<p><code>to_html(self, request, queryset, view)</code></p>
<p>The method should return a rendered HTML string.</p>
<h2 id="pagination-schemas"><a class="toclink" href="#pagination-schemas">Pagination &amp; schemas</a></h2>
<p>You can also make the filter controls available to the schema autogeneration
that REST framework provides, by implementing a <code>get_schema_fields()</code> method. This method should have the following signature:</p>
<p><code>get_schema_fields(self, view)</code></p>
<p>The method should return a list of <code>coreapi.Field</code> instances.</p>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third party packages</a></h1>
<p>The following third party packages provide additional filter implementations.</p>
<h2 id="django-rest-framework-filters-package"><a class="toclink" href="#django-rest-framework-filters-package">Django REST framework filters package</a></h2>
<p>The <a href="https://github.com/philipn/django-rest-framework-filters">django-rest-framework-filters package</a> works together with the <code>DjangoFilterBackend</code> class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.</p>
<h2 id="django-rest-framework-full-word-search-filter"><a class="toclink" href="#django-rest-framework-full-word-search-filter">Django REST framework full word search filter</a></h2>
<p>The <a href="https://github.com/trollknurr/django-rest-framework-word-search-filter">djangorestframework-word-filter</a> developed as alternative to <code>filters.SearchFilter</code> which will search full word in text, or exact match.</p>
<h2 id="django-url-filter"><a class="toclink" href="#django-url-filter">Django URL Filter</a></h2>
<p><a href="https://github.com/miki725/django-url-filter">django-url-filter</a> provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django <code>QuerySet</code>s.</p>
<h2 id="drf-url-filters"><a class="toclink" href="#drf-url-filters">drf-url-filters</a></h2>
<p><a href="https://github.com/manjitkumar/drf-url-filters">drf-url-filter</a> is a simple Django app to apply filters on drf <code>ModelViewSet</code>'s <code>Queryset</code> in a clean, simple and configurable way. It also supports validations on incoming query params and their values. A beautiful python package <code>Voluptuous</code> is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements.</p>
            

          </div> <!--/span-->
        </div> <!--/row-->
      </div> <!--/.fluid-container-->
    </div> <!--/.body content-->
    <div id="push"></div>
  </div> <!--/.wrapper -->

  <footer class="span12">
    <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.
    </p>
  </footer>

  <!-- Le javascript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script async src="../../../fund.django-rest-framework.org/sidebar_include.js"></script>
  <script src="../../js/jquery-1.8.1-min.js"></script>
  <script src="../../js/prettify-1.0.js"></script>
  <script src="../../js/bootstrap-2.1.1-min.js"></script>
  <script src="../../js/theme.js"></script>

  <script>var base_url = '../../index.html';</script>
  
  <script src="../../search/main.js" defer></script>
  

  <script>
    var shiftWindow = function() {
      scrollBy(0, -50)
    };

    if (location.hash) shiftWindow();
    window.addEventListener("hashchange", shiftWindow);

    $('.dropdown-menu').on('click touchstart', function(event) {
      event.stopPropagation();
    });

    // Dynamically force sidenav/dropdown to no higher than browser window
    $('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);

    $(function() {
      $(window).resize(function() {
        $('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
      });
    });
  </script>
</body>


<!-- Mirrored from www.django-rest-framework.org/api-guide/filtering/ by HTTrack Website Copier/3.x [XR&CO'2014], Sun, 13 Sep 2020 09:31:03 GMT -->
</html>